import React, { useState, useContext } from 'react';
import { Button, Input, Upload, message, Image, Row, Col } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import './css/VideoUploadPage.css';
import axios from 'axios';
import BarChart from './views/home';
import Line from './views/Charts/Line';
import { Divider } from 'antd';
import ImgCrop from 'antd-img-crop';
import { usePlateAndFace } from '../store';
import { AppStateContext } from '../store/context';

const { Dragger } = Upload;

const App = () => {
  // const [plateNum, setPlateNum, faceList, setFaceList] = usePlateAndFace();
  const { plateNum, setPlateNum, faceList, setFaceList } = useContext(AppStateContext);
  const [videoUrl, setVideoUrl] = useState('');
  const [fileList, setFileList] = useState([]);

  const [frameData, setFrameData] = useState({});
  const [loading, setLoading] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const [personData, setPersonData] = useState([]);
  const [carData, setCarData] = useState([]);
  const [imgurl, setImgurl] = useState('');
  const [carurl, setCarurl] = useState('');
  const [faceurl, setFaceurl] = useState('');
  const [detectedCar, setDetectedCar] = useState(false);
  const [detectedFace, setDetectedFace] = useState(false);

  const [lp, setlp] = useState('');

  const onFaceChange = (info) => {
    setFaceList(info.fileList);
    console.log(info.fileList);
    // info.file.status = 'done';
    // setTimeout(() => {
    //   info.file.status = 'done';
    // }, 500)
  };


  const handleVideoChange = (info) => {
    console.log(info);
    info.file.status = 'done';

  };

  const handleUrlChange = (e) => {
    setVideoUrl(e.target.value);
    console.log(videoUrl);
  };

  const handleLpChange = (e) => {
    setlp(e.target.value);
  }

  const onPreview = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };

  const startButtonHandler = () => {
    if (videoUrl || fileList.length > 0) {
      message.success('视频已准备好播放');
      console.log(fileList);
    } else {
      message.error('请上传视频或输入视频流地址');
    }
  };

  const customRequest = ({ file }) => {
    console.log(file);
    setTimeout(() => {
      file.status = 'done';
      file.response = {};
      // 更新文件列表
      setFileList([...fileList, file]);
    }, 10);
  };

  const customRequestFace = ({ file, onSuccess }) => {
    setTimeout(() => {
      // file.status = 'done';
      // file.response = {};
      onSuccess(file)
      // 更新文件列表
      // setFaceList([...faceList, file]);
    }, 1000);
  };

  async function uploadAndProcessVideo() {
    setLoading(true);
    const formData = new FormData();
    if (fileList.length > 0) {
      formData.append('video', fileList[0]);
    }
    else if (videoUrl) {
      const face_base64_list = faceList.map(file => {
        return file.thumbUrl.split(',')[1];
      })
      formData.append('video_url', videoUrl);
      formData.append('lp', lp);
      formData.append('face_image', JSON.stringify(face_base64_list));
    }
    console.log(formData);

    // console.log(JSON.stringify(face_base64_list));
    try {
      // 发送视频文件到服务器
      let response
      if (fileList.length > 0) {
        response = await fetch('http://192.168.6.168:5000/save_video', {
          method: 'POST',
          body: formData
        });
      }
      else if (videoUrl) {
        response = await fetch('http://192.168.6.168:5000/upload_video', {
          method: 'POST',
          body: formData
        });
      }

      if (!response.ok) {
        throw new Error(`HTTP 错误！状态: ${response.status}`);
      }
      else {
        message.success('处理成功')
      }

      console.log('收到响应:', response);
      setLoading(false);
      setLoaded(true);

      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let buffer = '';

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        let boundaryIndex;

        while ((boundaryIndex = buffer.indexOf('--frame')) !== -1) {
          const chunk = buffer.slice(0, boundaryIndex).trim();
          buffer = buffer.slice(boundaryIndex + '--frame'.length).trim();

          if (chunk) {
            const headerEndIndex = chunk.indexOf('\r\n\r\n');
            if (headerEndIndex !== -1) {
              const jsonPart = chunk.slice(headerEndIndex + 4);
              try {
                const totaldata = JSON.parse(jsonPart);

                let tmpobj = {
                  'person': 0,
                  'car': 0,
                };

                for (let bbox of totaldata['bboxes']) {
                  tmpobj[bbox[4]] += 1;
                }

                setFrameData(tmpobj);
                setPersonData(prevData => [...prevData, tmpobj['person']]);
                setCarData(prevData => [...prevData, tmpobj['car']]);
                setImgurl(totaldata['image_base64']);
                console.log(totaldata['is_face_match']);
                if (totaldata['is_car_match']) {
                  setDetectedCar(true);
                  if (totaldata['car_base64']) {
                    setCarurl(totaldata['car_base64_list'][0]);
                  }
                  else {
                    setCarurl(totaldata['image_base64']);
                  }
                }
                if (totaldata['is_face_match']) {

                  setDetectedFace(true);
                  if (totaldata['face_base64_list'].length > 0) {
                    setFaceurl(totaldata['face_base64_list'][0]);
                  }
                  else {
                    setFaceurl(totaldata['image_base64']);
                  }
                }
              } catch (e) {
                console.error('解析JSON数据时出错:', e);
              }
            }
          }
        }
      }

    } catch (error) {
      console.error('Error uploading and processing video:', error);
    }
  }


  return (
    <>
      {
        !loaded ?
          <div className="container">
            <div className="content">
              <Divider orientation='left' style={{

              }}>
                <h2>数据源</h2>
              </Divider>
              <Input
                placeholder="输入视频流地址"
                value={videoUrl}
                onChange={handleUrlChange}
                className="input-url"
              />

              <Dragger
                customRequest={customRequest}
                onChange={handleVideoChange}
                style={{
                  marginBottom: 15,
                }}
              >
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p className="ant-upload-text">点击或拖拽视频到此</p>
                <p className="ant-upload-hint">
                  仅支持单个上传
                </p>
              </Dragger>

              <Divider orientation='left'><h2>需检测信息</h2></Divider>
              <Input
                placeholder="输入需要检测的车牌号"
                value={lp}
                onChange={handleLpChange}
                className="input-url"
              />
              <ImgCrop>
                <Upload
                  customRequest={customRequestFace}
                  onChange={onFaceChange}
                  onPreview={onPreview}
                  style={{
                    marginBottom: 15,
                  }}
                  listType='picture-card'
                  fileList={faceList}
                // type='picture-card'
                >
                  {faceList.length < 5 && '+ 上传人脸'}
                </Upload>
              </ImgCrop>
              <Button
                type="primary"
                size="large"
                onClick={uploadAndProcessVideo}
                className="start-button"
                style={{
                  marginTop: 15
                }}
                loading={loading}
              >
                开始
              </Button>
            </div>
          </div> :
          <Row gutter={[32, 16]} >
            <Col span={6}>
              <h3>目标人脸</h3>
            </Col>
            <Col span={12}><h3>检测结果</h3></Col>
            <Col span={6}><h3>目标车牌</h3></Col>
            <Col span={6}>
              <img src={faceurl ||
                ""
              } alt="Example Image" style={{
                objectFit: 'contain',
                width: '100%',
                height: 266
              }}
              />
            </Col>
            <Col span={12} >
              <img src={imgurl ||
                ""
              } alt="Example Image" style={{
                objectFit: 'contain',
                width: '100%',
                height: 266
              }}
              />
            </Col>
            <Col span={6}>
              <img src={carurl ||
                ""
              } alt="Example Image" style={{
                objectFit: 'contain',
                width: '100%',
                height: 266
              }}
              />
            </Col>
            <Col span={12}>
              <BarChart data={frameData} />
            </Col>
            <Col span={12}>
              <Line data={[personData, carData]} />
            </Col>
          </Row>
        // <div className="container" style={{
        //   flexDirection: 'column',
        //   display: 'flex',
        // }}>
        //   <h2>
        //     {detectedCar ? '检测到车牌号为' + lp + '的车辆' : '未检测到结果'}
        //   </h2>
        //   <h2>

        //     {detectedFace ? '检测到人脸' : '未检测到人脸'}
        //   </h2>
        //   <div className="top-row">
        //     <div className="left-image" style={{
        //       border: '1px solid #ccc',
        //     }}>
        //       <img src={faceurl} alt="Example Image" style={{ width: '50%' }} />
        //       <img src={carurl} alt="Example Image" style={{ width: '50%' }} />

        //     </div>
        //     <div className="right-chart" style={{
        //       border: '1px solid #ccc',
        //     }}>
        //       <div className="bar-chart">
        //         <BarChart data={frameData} />
        //       </div>
        //     </div>
        //   </div>
        //   <div className="bottom-chart" style={{
        //     border: '1px solid #ccc',
        //   }}>
        //     {/* Replace with your actual Line component */}
        //     <Line data={[personData, carData]} />
        //   </div>
        // </div>
      }

    </>
  );
};


export default App;